package org.ytor.common.util.excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.ytor.common.enums.ExcelVersion;
import org.ytor.common.exception.BaseException;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * created by yangtong on 2025/5/29 23:05:50
 * <br/>
 */
public class WorkbookGen {
    public static Workbook gen(InputStream excelIs) {
        try {
            //确保输入流为包装流
            if (!(excelIs instanceof BufferedInputStream)) {
                excelIs = new BufferedInputStream(excelIs);
            }
            ExcelVersion version = ExcelVersion.parseVersion(excelIs);
            return switch (version) {
                case V03 -> new HSSFWorkbook(excelIs);
                case V07 -> new XSSFWorkbook(excelIs);
                case V07_PLUS -> throw new BaseException("不支持的类型:V07_PLUS");
            };
        } catch (IOException e) {
            throw new BaseException(e);
        }
    }

    public static Workbook gen(ExcelVersion version) {
        return switch (version) {
            case V03 -> new HSSFWorkbook();
            case V07 -> new XSSFWorkbook();
            case V07_PLUS -> new SXSSFWorkbook();
        };
    }
}
